package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"os/user"
	"strings"
)

// HomeDirFlag 当前用户家目录标识符
const HomeDirFlag = "~"

// ConvertHomeDir convert ~ to user's home dir
func ConvertHomeDir(raw string) (string, error) {
	raw = strings.TrimSpace(raw)

	if !strings.HasPrefix(raw, HomeDirFlag) {
		return raw, nil
	}
	user, err := user.Current()
	if err != nil {
		return raw, err
	}
	return strings.Replace(raw, HomeDirFlag, user.HomeDir, 1), nil
}

func ExecCmd(osType string, args []string) ([]byte, error) {

	if osType == "nx" {
		return execScript(strings.Join(args, " "))
	}
	if osType == "win" {
		newArgs := append([]string{"/C"}, args...)
		return exec.Command("cmd", newArgs...).Output()
	}
	return nil, fmt.Errorf("invalid os type")
}

func execScript(script string) ([]byte, error) {

	// 生成临时文件
	file, err := ioutil.TempFile("", "tmp-script")
	if err != nil {
		return nil, err
	}
	defer os.Remove(file.Name())
	defer file.Close()

	if _, err = file.WriteString(script); err != nil {
		return nil, err
	}
	file.Close()

	var cmd = exec.Command("/bin/bash", file.Name())
	return cmd.Output()
}
